﻿using MediatR;
using ProductionManagement.Application.Command.PreProductionCommand;
using ProductionManagement.Infrstructre.lmp;
using ProductionManagement.Infrstructre.lnterface;
using SqlSugar;

namespace ProductionManagement.Application.CommandHandler.PreProductionCommandHandler
{
    /// <summary>
    /// 删除预生产单命令处理器
    /// </summary>
    public class PreProductionDelCommandHandler : IRequestHandler<PreProductionDelCommand, int>
    {
        private readonly IPreProductionRepository _preProductionRep;
        private readonly IPreProducsRepository _preProducsRep;
        private readonly ISqlSugarClient db;
        public PreProductionDelCommandHandler(IPreProductionRepository preProductionRep, IPreProducsRepository preProducsRep, ISqlSugarClient db)
        {
            this._preProductionRep = preProductionRep;
            this._preProducsRep = preProducsRep;
            this.db = db;
        }

        public async Task<int> Handle(PreProductionDelCommand request, CancellationToken cancellationToken)
        {
            // 开启事务
            db.Ado.BeginTran();
            try
            {
                var list = (await _preProductionRep.GetAll()).Where(x => request.PreProductionId.Contains(x.PreProductionId)).ToList();
                foreach (var material in list)
                {
                    material.IsDel = true;
                    material.DelName = request.DelName;
                    material.DelTime = DateTime.Now;
                    var item = (await _preProducsRep.GetAll()).Where(x => x.PPDocuNumber == material.PPDocuNumber).ToList();
                    foreach (var subpiece in item)
                    {
                        subpiece.IsDel = true;
                        subpiece.DelName = request.DelName;
                        subpiece.DelTime = DateTime.Now;
                        await _preProducsRep.UpdAsync(subpiece);
                    }
                    await _preProductionRep.UpdAsync(material);
                }
                db.Ado.CommitTran();
            }
            catch (Exception ex)
            {
                db.Ado.RollbackTran();
                throw ex;
            }
            finally
            {
                db.Ado.Close();
            }
            return 1;
        }
    }
}
